﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MediSIIM.BizComponent.HangZhouSYB;
using MediSIIM.BizComponent.HangZhouSYBInterface;
using System.IO;
using SWSoft.Framework;
using System.Threading;
using System.Diagnostics;

namespace HangZhouSYB
{
    public partial class Form1 : Form
    {
        string ywzqh = "";
        string caozuoydm = "";
        string YBYYDM;
        public Form1()
        {
            InitializeComponent();
            CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                var caozuoy = textBox2.Text.Split('|');
                var inputstr1 =
                "04|" +//项目编码:04
              textBox1.Text + "|" +//需要下载的业务周期号
                "00|" +//医院交易流水号:00
                "00|";//门诊号(住院号):00
                var tradeType = new TradeType() { TradeTypeNo = EnumTradeTypeNo.JIAOYIXXXZ, MenzhenZhuyuan = MENZHENZHUYUAN.GONGYONG };
                var callparam = new HangZhouSYBTradeParms(tradeType, caozuoy[0], inputstr1, "", YBYYDM, "", "00", caozuoy[1]);
                callparam.YBCall(callparam);
                var fileinfo = new FileInfo(String.Format("{0}\\down.txt", Application.StartupPath));
                #region 明细
                if (fileinfo.Exists)
                {
                    using (var sw = new StreamReader(fileinfo.FullName))
                    {
                        var table = new DataTable();
                        table.Columns.Add("机构编号");
                        table.Columns.Add("住院门诊号");
                        table.Columns.Add("交易流水号");
                        table.Columns.Add("单据号");
                        table.Columns.Add("交易类型");
                        table.Columns.Add("单位编号");
                        table.Columns.Add("个人编号");
                        table.Columns.Add("结算日期");
                        table.Columns.Add("医疗类别");
                        table.Columns.Add("医疗人员类别");
                        table.Columns.Add("医疗费总额");
                        table.Columns.Add("上次进入统筹医疗费用累计");
                        table.Columns.Add("本次进入统筹医疗费用金额");
                        table.Columns.Add("帐户封顶");
                        table.Columns.Add("上次个人帐户余额");
                        table.Columns.Add("个人自费金额");
                        table.Columns.Add("乙类药品个人自理");
                        table.Columns.Add("特检个人自理");
                        table.Columns.Add("特治个人自理");
                        table.Columns.Add("起付标准自付金额");
                        table.Columns.Add("起付标准帐户支付金额");
                        table.Columns.Add("起付标准现金支付");
                        table.Columns.Add("分段自理金额");
                        table.Columns.Add("起付以上自理帐户支付");
                        table.Columns.Add("起付以上自理现金支付");
                        table.Columns.Add("分段1自理");
                        table.Columns.Add("分段2自理");
                        table.Columns.Add("分段3自理");
                        table.Columns.Add("分段4自理");
                        table.Columns.Add("分段5自理");
                        table.Columns.Add("超过封顶线个人自付金额");
                        table.Columns.Add("本年帐户支付金额");
                        table.Columns.Add("个人帐户支付金额");
                        table.Columns.Add("统筹支付金额");
                        table.Columns.Add("个人现金支付");
                        table.Columns.Add("救助金支出金额");
                        table.Columns.Add("公务员补助支出金额");
                        table.Columns.Add("审核扣款金额");
                        table.Columns.Add("帐户冲减日期");
                        table.Columns.Add("帐户冲减标志");
                        table.Columns.Add("报销标志");
                        table.Columns.Add("经办人");
                        table.Columns.Add("经办日期");
                        table.Columns.Add("支付流水号");
                        table.Columns.Add("支付标志");
                        table.Columns.Add("财务接口流水号");
                        table.Columns.Add("逻辑校验位");
                        table.Columns.Add("公务员上次累计门诊起伏线");
                        table.Columns.Add("公务员本次进入门诊起伏线");
                        table.Columns.Add("公务员门诊起伏线历年账户支付");
                        table.Columns.Add("公务员门诊分段自负金额");
                        table.Columns.Add("退休人员中断享受类别");
                        table.Columns.Add("医院流水号");
                        table.Columns.Add("撤销交易流水号");
                        table.Columns.Add("业务周期号");

                        while (!sw.EndOfStream)
                        {
                            var line = sw.ReadLine().Replace('\t', '|');
                            var strs = line.Split('|');
                            var newrow = table.NewRow();
                            newrow.ItemArray = new List<object>(strs).GetRange(0, 50).ToArray();
                            table.Rows.Add(newrow);
                        }
                        dataGridView1.DataSource = table;
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }
        private void Form1_Load(object sender, EventArgs e)
        {
            YBYYDM = DBVisitor.ExecuteModel("SELECT * From yb_bxlbxx where ylbxid=102")["YBYYDM"].ToString();
            try
            {
                var entry = DBVisitor.ExecuteModel("SELECT * FROM yb_ywzcxx yy WHERE yy.czyhgh='DBA' AND yy.yhywzt=1 AND yy.ylbxid=102 and ywxtlb=2");
                ywzqh = entry["YWZQHM"] + "";
                caozuoydm = entry["CZYHGH"] + "";
                comboBox1.SelectedIndex = 0;
            }
            catch (Exception)
            {
            }
        }
        string bianhao;
        private void button2_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(new WaitCallback(o =>
            {
                bianhao = comboBox1.SelectedItem.ToString().Split('.')[0];
                var tradeType = new TradeType() { TradeTypeNo = EnumTradeTypeNo.YaoPinMLGX, MenzhenZhuyuan = MENZHENZHUYUAN.GONGYONG };
                var indata = "" +
                    bianhao + "|" +//项目编码
                    dateTimePicker1.Text + //下载数据开始日期 YYYYMMDD
                    "|";
                var callparam = new HangZhouSYBTradeParms(tradeType, ywzqh, indata, "|", YBYYDM, "", "00", caozuoydm);
                try
                {
                    callparam.YBCall(callparam);
                    MessageBox.Show(callparam.OutData);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                var fileinfo = new FileInfo(Application.StartupPath + "\\down.txt");
                if (callparam.OutData.Split('|')[0] != "0")
                {
                    File.WriteAllText(Application.StartupPath + "\\" + comboBox1.SelectedItem.ToString().Split('.')[1], File.ReadAllText(fileinfo.FullName));
                }
                if (fileinfo.Exists)
                {
                    var table = new DataTable();
                    using (var sw = new StreamReader(fileinfo.FullName, Encoding.Default))
                    {
                        while (!sw.EndOfStream)
                        {
                            var line = sw.ReadLine().Split('\t');
                            if (table.Columns.Count == 0)
                            {
                                for (int i = 0; i < line.Length; i++)
                                {
                                    table.Columns.Add("Column" + i);
                                }
                            }
                            var newrow = table.NewRow();
                            newrow.ItemArray = line;
                            table.Rows.Add(newrow);
                        }
                        dataGridView2.DataSource = table;
                    }
                }
            }));
        }

        private void 更新诊疗材料对照目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileinfo = new FileInfo(Application.StartupPath + "\\材料和项目对照表KA56.txt");
            if (fileinfo.Exists)
            {
                #region
                using (var sw = new StreamReader(fileinfo.FullName, Encoding.Default))
                {
                    var delete = "delete from yb_cldzzd where zdjlxh in (";
                    var cmdtext = " INSERT INTO yb_cldzzd(zdjlxh,ylbxid,ybzcbh,zlcldm,syzldm,syzlmc," +
     "sybzsm,   " +
     "ybcldm,   " +
     "hzsrm1,   " +
     "hzsrm2,  " +
     "hzsrm3,  " +
     "ybqyrq,    " +
     "ybzzrq    " +
 ")                   ";
                    while (!sw.EndOfStream)
                    {
                        var strs = sw.ReadLine().Split('\t');
                        delete += strs[9] + ",";
                        var ybdm = strs[0].Substring(0, 2) + "000000" + strs[0].Substring(8);
                        cmdtext += " SELECT        " +
                           strs[9] + "," +
                               "102," +
                               "1," +
                               "'" + ybdm.ToUpper() + "', " +
                               "'" + strs[2].ToUpper() + "', " +
                               "'" + strs[1] + "'," +
                               "NULL," +
                               "'" + strs[0].ToUpper() + "'," +
                               "'" + "" + "', " +
                               "'', " +
                               "'', " +
                               "'" + DateTime.Parse(strs[7]).ToString("yyyyMMdd") + "'," +
                               (string.IsNullOrEmpty(strs[8]) ? "null" : ("'" + DateTime.Parse(strs[8]).ToString("yyyyMMdd")) + "'") +
                           " from dual union\r\n";
                    }
                    //var tran = data.ThisConnection.BeginTransaction();
                    cmdtext = cmdtext.Substring(0, cmdtext.Length - 7);
                    delete = delete.TrimEnd(',') + ")";
                    try
                    {
                        DBVisitor.ExecuteNonQuery(delete);
                        DBVisitor.ExecuteNonQuery(cmdtext);
                        //tran.Commit();
                    }
                    catch (Exception ex)
                    {
                        //tran.Rollback();
                        MessageBox.Show(ex.Message);
                    }
                }
                #endregion
            }
        }

        private void 更新药品目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileinfo = new FileInfo(String.Format("{0}\\目录数据\\药品目录KA02.txt", Application.StartupPath));
            var YBZCBH = DBVisitor.ExecuteModel("SELECT * FROM YB_BXZCXX where ylbxid=102")["YBZCBH"];
            if (fileinfo.Exists)
            {
                var list = new List<string>();
                using (var sw = new StreamReader(fileinfo.FullName, Encoding.Default))
                {
                    while (!sw.EndOfStream)
                    {
                        list.Add(sw.ReadLine());
                    }
                }
                var txtxls = "";
                foreach (var item in list)
                {
                    var strs = item.Split('\t');
                    txtxls += "\t" + 102 + "\t" +
                     YBZCBH + "\t" +
                     strs[0].ToUpper() + "\t" +
                     strs[1].ToUpper() + "\t" +
                     strs[3] + "\t" +
                     strs[35] + "\t" +
                     strs[4] + "\t" +
                     strs[38] + "\t" +
                     strs[37] + "\t";
                    if (strs[0].StartsWith("z"))
                    {
                        txtxls += "12" + "\t" +
                         2 + "\t";
                    }
                    else if (strs[0].StartsWith("y"))
                    {
                        txtxls += "13" + "\t" +
                        4 + "\t";
                    }
                    else
                    {
                        txtxls += "11" + "\t" +
                        1 + "\t";
                    }
                    txtxls += "" + "\t" +
                    GetDecimal(strs[23]) + "\t" +
                    strs[24] + "\t" +
                    strs[25] + "\t" +
                    GetDecimal(strs[14]) + "\t" +
                    GetDecimal(strs[29]) + "\t" +
                    GetDecimal(strs[15]) + "\t" +
                    strs[16] + "\t" +
                    strs[21] + "\t" +
                    strs[8] + "\t" +
                    strs[21] + "\t" +
                     (GetDecimal(strs[7]) == 1 ? 1 : 0) + "\t" +
                       0 + "\t" +
                     GetDecimal(strs[12]) + "\t" +
                       "\t" +
                      "\t" +
                      "\t" +
                     GetDecimal(strs[12]) + "\t" +
                     GetDecimal(strs[12]) + "\t" +
                     "\t" +
                       "\t" +
                     strs[10] + "\t" +
                     strs[11] + "\t" +
                     strs[10] + "\t" +
                     strs[41] + "\t" +
                     strs[36] + "\t" +
                     strs[0] + "\t" +
                     (strs[18] == "2" ? 1 : 0) + "\t" +
                     DateTime.Parse(strs[22]).ToString("yyyyMMdd") + "\t" +
                   "\t" +
                      (strs[18] == "2" ? 1 : 0) + "\t" +
                      GetDecimal(strs[39]) + "\t" +
                      strs[40] + "\t" +
                      GetAutoNumber("SEQ_YB_YPDMZD") + "\r\n";
                }
                var sfd = new SaveFileDialog();
                sfd.Filter = "*.csv|*.csv";
                sfd.FileName = "药品目录";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, txtxls, Encoding.UTF8);
                }
            }
        }

        private decimal GetAutoNumber(string seqname)
        {
            var cmdText = string.Format("SELECT {0}.NEXTVAL SEQNUM FROM dual", seqname);
            try
            {
                return (decimal)DBVisitor.ExecuteScalar(cmdText);
            }
            catch (Exception ex)
            {
                throw new Exception("获取序列号异常，错误信息：" + ex.Message);
            }
        }

        public decimal GetDecimal(object obj)
        {
            obj = obj ?? 0;
            decimal d = 0;
            if (decimal.TryParse(obj.ToString(), out d))
            {
                return d;
            }
            return 0;
        }

        private void 更新诊疗材料目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileinfo = new FileInfo(String.Format("{0}\\目录数据\\诊疗材料目录KA03.txt", Application.StartupPath));
            var YBZCBH = DBVisitor.ExecuteModel("SELECT * FROM YB_BXZCXX where ylbxid=102")["YBZCBH"];
            if (fileinfo.Exists)
            {
                var list = new List<string>();
                using (var sw = new StreamReader(fileinfo.FullName, Encoding.Default))
                {
                    while (!sw.EndOfStream)
                    {
                        list.Add(sw.ReadLine());
                    }
                }
                var txtxls = "";

                #region 诊疗目录更新

                var deletesql = string.Format("DELETE FROM YB_ZLDMZD WHERE YLBXID={0} AND YBZCBH={1} AND ybzldm IN (", 102, YBZCBH);
                foreach (var item in list)
                {
                    var strs = item.Split('\t');
                    deletesql += string.Format("'{0}',", strs[0].ToUpper());
                    txtxls += "\t" +
                   102 + "\t" +
                   YBZCBH + "\t" +
                   strs[0].ToUpper() + "\t" +
                   "\t" +
                   strs[2] + "\t" +
                    "\t" +
                    strs[4] + "\t" +
                    strs[3] + "\t" +
                    "\t" +
                    ((strs[12].IndexOf("限") >= 0 && !string.IsNullOrEmpty(strs[12])) ? strs[12] : "") + "\t" +
                    strs[15] + "\t" +
                   "\t" +
                  strs[11] + "\t" +
                   "\t" +
                   0 + "\t" +
                   "\t" +
                   "\t" +
                   "\t" +
                   "\t" +
                   (string.IsNullOrEmpty(strs[26]) ? "0" : strs[26]) + "\t" +
                    strs[6] + "\t" +
                    strs[5] + "\t" +
                    "\t" +
                    "\t" +
                    (strs[7] == "2" ? 1 : 0) + "\t" +
                    DateTime.Parse(strs[8]).ToString("yyyyMMdd") + "\t" +
                    "\t" +
                    "\t" +
                   GetAutoNumber("SEQ_YB_ZLDMZD") + "\r\n";
                }
                var sfd = new SaveFileDialog();
                sfd.Filter = "*.csv|*.csv";
                sfd.FileName = "yb_zldmzd";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, txtxls, Encoding.Default);
                }
                sfd.Filter = "*.sql|*.sql";
                sfd.FileName = "del_yb_zldmzd";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, deletesql, Encoding.Default);
                }
                #endregion
            }
        }

        private void 更新疾病目录ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var fileinfo = new FileInfo(String.Format("{0}\\目录数据\\病种库KA06.txt", Application.StartupPath));
            var YBZCBH = DBVisitor.ExecuteScalar("SELECT YBZCBH FROM YB_BXZCXX where ylbxid=102");
            if (fileinfo.Exists)
            {
                var list = new List<string>();
                using (var sw = new StreamReader(fileinfo.FullName, Encoding.Default))
                {
                    while (!sw.EndOfStream)
                    {
                        list.Add(sw.ReadLine());
                    }
                }
                var txtxls = "";

                foreach (var item in list)
                {
                    var strs = item.Split('\t');
                    txtxls += "\t" + 102 + "\t" +
                     strs[0].ToUpper() + "\t" +
                     strs[0].ToUpper() + "\t" +
                     strs[1] + "\t" +
                     "\t" +
                     strs[0].ToUpper() + "\t" +
                     strs[4] + "\t" +
                     "\t" +
                     GetDecimal(strs[2]) + "\t" +
                      "\t" +
                     (string.IsNullOrEmpty(strs[3]) ? Util.GetStringSpellFirstCode(strs[1]).ToUpper() : strs[3].ToUpper()) + "\t" +
                     strs[4] + "\t" +
                     "\t" +
                       "\t\r\n";
                }
                var sfd = new SaveFileDialog();
                sfd.Filter = "*.csv|*.csv";
                sfd.FileName = "yb_jbdmzd";
                if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    File.WriteAllText(sfd.FileName, txtxls, Encoding.Default);
                }
            }
        }
    }
}
